<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>vuex</title>
	<script src="node_modules/vue/dist/vue.js"></script>
	<script src="node_modules/vuex/dist/vuex.min.js"></script>
</head>
<body>
	<div id="app">
		<h2>{{msg}}</h2>
		<button @click="add">增加</button>
		<button @click="minus">减少</button>
		<button @click="changeName">更换用户</button>
		<counter></counter>
	</div>
	<script>
		const counter = {
			template:`
				<div>
					<div>count:{{count}}</div>
					<div>userName:{{userName}}</div>
				</div>
			`,
			computed:{
				count(){
					return this.$store.state.count;
				},
				name(){
					return this.$store.state.name;
				},
				userName(){
					return this.$store.getters.userName;
				}
			}
		}

		const store = new Vuex.Store({
			state:{
				count:10,
				name:'jack'
			},
			getters:{
				userName(state){
					return state.name + ',hello';
				}
			},
			mutations:{
				increment(state,num){
					state.count += num;
				},
				decrement(state,num){
					state.count -= num;
				},
				updateName(state,username){
					state.name = username;
				}
			},
			actions:{
				incrementAction(context,num){
					context.commit('increment',num);
				}
			}
		})

		new Vue({
			el:'#app',
			store,
			data:{
				msg:'vueX的使用'
			},
			components:{
				counter
			},
			methods:{
				add(){
					//this.$store.commit('increment',2);
					this.$store.dispatch('incrementAction',5);
				},
				minus(){
					this.$store.commit('decrement',4);
				},
				changeName(){
					this.$store.commit('updateName','汤姆克鲁斯');
				}
			}
		})
	</script>
</body>
</html>